#include "vcd-vm-connect.h"
#include "vcd-get-vm-info.h"
#include "vcd-conf/vcd-conf.h"
#include "vcd-json-parser.h"
#include "vcd-common.h"
#include "vcd-linux-ui/vcd-message-dialog.h"
#include "vcd-linux-ui/vcd-logined-window.h"
#include "vcd-util.h"
#include "vcd-download.h"
#include "spicy.h"
#include "vcd-vm-rdp-connect.h"
#include "vcd-get-login-ticket.h"
#include "vcd-new-login-mode.h" 
#include "vcd-vm-status-control.h"
#include "vcd-common-api/vcd-com-reconnect.h"

static void clear_old_infomation(void);
static void save_connect_data(void);
static void spice_proxy_data_free(spice_proxy_data* d);

static void save_connect_data(void)
{
    strncpy(g_vcd_conf->node, connect_data.node, sizeof(g_vcd_conf->node));
    g_vcd_conf->vmid = connect_data.vmid;
    strncpy(g_vcd_conf->public_id, connect_data.public_id, sizeof(g_vcd_conf->public_id));
    update_vcd_conf();
}

gboolean button_enter_callback_task(gpointer data)
{
    g_return_val_if_fail(data != 0, FALSE);

    int ret = 0;
    spice_proxy_data d;
    char useip[80];
    char useport[80];
    struct vcd_conf* tmp_vcd_conf = g_vcd_conf;
    struct network_response *res = (struct network_response *)data;
    char *memory = (char*)res->memory;
    char error[200] = {0};

    memset(&d, 0, sizeof(d));

    if (!memory) {        
        sprintf(error, " 请求连接数据超时!(vmid=%d) ", connect_data.vmid);
        LOG_ERROR("error in get spiceproxy");
        message_box(error);
        goto fail;
    }
    //if (PRIVATE_LOGIN == tmp_vcd_conf->login_way) {

    ret = json_parser_get_spice_proxy(memory, &d);
    if (ret != 0) {
        M_DEBUG("parse json fail:%s", memory);
        goto fail;
    }
    //M_DEBUG(memory);
    if (d.success != 1) {
        char strMsg[500] = {0};
        sprintf(strMsg, "VM %d not running\n", connect_data.vmid);
        if (d.fail_msg) {
            if (strcmp(strMsg, d.fail_msg) == 0) {
                start_vm_sys(&connect_data);
                vcd_com_reconnect_set_status(ReconVmUnStart);
            } else if(strstr(d.fail_msg,"no spice port") && tmp_vcd_conf->local_model_check_status){
                char* unix_sock = vcd_common_get_unix_sock(connect_data.vmid);
                M_DEBUG("%s,try connect unix sock: %s",d.fail_msg,unix_sock);
                spicy_connect_with_unix(unix_sock);
                goto fail;
            }
            else {
                message_box(d.fail_msg);
            }
        }
        goto fail;
    }

    if (strcmp(connect_data.status, "suspended") == 0 ||
            strcmp(connect_data.status, "paused") == 0) {
        M_DEBUG("connect_data.status=%s", connect_data.status);
        resume_vm_sys(&connect_data);
        goto fail;
    }

    memset(useip, 0, sizeof(useip));
    memset(useport, 0, sizeof(useport));

    if (d.proxy == NULL || d.password == NULL) {
        M_DEBUG("proxy:%p password:%p", d.proxy, d.password);
        goto fail;
    }

    //parse ip and port
    ret = sscanf(d.proxy, "%*[^/]//%[^:]:%s", useip, useport);;
    if (ret != 2) {
        char szbuf[255];
        snprintf(szbuf, sizeof(szbuf), "invalid proxy:%s", d.proxy);
        message_box(szbuf);
        M_DEBUG("%s", szbuf);
        goto fail;
    }

    memset(useport, 0, sizeof(useport));
    snprintf(useport, sizeof(useport), "%d", d.tls_port);

    if (tmp_vcd_conf->login_mode == EMODE_NEW) {
        check_num_ctx *ctx = (check_num_ctx*)malloc(sizeof(check_num_ctx));
        if (ctx) {
            ctx->ip = strdup(useip);
            ctx->password = strdup(d.password);
            ctx->tls_port = strdup(useport);
            /*若成功检测，则按照新模式去连接这边直接不用管了存储一下数据，就退出*/
            if (check_new_mode_connect(ctx) == 0) {
                save_connect_data();
                spice_proxy_data_free(&d);
                network_response_free(&res);
                return FALSE;
            }
            goto fail;
        }
    }

    //私有云直连的时候从proxy获取ip，使用我们自己的代理的时候也是从proxy获取ip。
    spicy_connect(useip, useport, d.password , NULL);
    // } else {
    //     if (json_object_get_int_member(obj1, "code"))
    //         obj2 = json_object_get_object_member(obj1, "data");
    //     else {
    //         delete_g_connect_label_and_spinner();
    //         if (strcmp(connect_data.status, "2") == 0)
    //             startSystemBox(&connect_data);
    //         else if (strcmp(connect_data.status, "5") == 0) {
    //             messageBox(" 云主机已欠费，请充值! ");
    //         }
    //         else {
    //             messageBox("     连接失败!     ");
    //         }
    //         g_object_unref(parser);
    //         return FALSE;
    //     }

    //     int port = json_object_get_int_member(obj2, "tls-port");
    //     char port_str[10];
    //     sprintf(port_str, "%d", port);
    //     spicy_connect(json_object_get_string_member(obj2, "host"), port_str, json_object_get_string_member(obj2, "password"), json_object_get_string_member(obj2, "proxy"));
    // }
    save_connect_data();
    spice_proxy_data_free(&d);
    network_response_free(&res);
    return FALSE;
fail:
    spice_proxy_data_free(&d);
    network_response_free(&res);
    delete_g_connect_label_and_spinner();
    return FALSE;
}

static void spice_proxy_data_free(spice_proxy_data* d)
{
    if (d == NULL)
        return;

    SAFE_FREE(d->fail_msg);
    SAFE_FREE(d->host);
    SAFE_FREE(d->password);
    SAFE_FREE(d->proxy);
    SAFE_FREE(d->title);
    SAFE_FREE(d->type);
}

static void clear_old_infomation(void)
{
    delete_g_connect_label_and_spinner();
    spicy_disconnect();
}

void button_enter(vm_info *enter_data)
{
    clear_old_infomation();

    struct vcd_conf* tmp_vcd_conf = g_vcd_conf;

    M_DEBUG("button_enter clicked vmid:%d, name:%s, node:%s, type:%s, server_ip:%s, system_type:%s,net0:%s",
            enter_data->vmid,
            enter_data->name,
            enter_data->node,
            enter_data->type,
            enter_data->server_ip,
            enter_data->system_type,
            enter_data->net0);

    /*connect_data在vcd-get-vm-info.c中的全局变量*/
    memcpy(&connect_data, enter_data, sizeof(vm_info));

    chanage_connect_status(TRUE);

    if (PRIVATE_LOGIN == tmp_vcd_conf->login_way)
    {
        if (strlen(connect_data.node) == 0 || connect_data.vmid == 0) {
            message_box("  自动登录失败！ ");//网络错误
            return;
        }

        char url[512] = {0};
        struct curl_slist *list = NULL;
        list = curl_slist_append(list, g_final_ticket);
        list = curl_slist_append(list, g_token);
        struct network_request_arg *network_task = (struct network_request_arg *)malloc(sizeof(struct network_request_arg));
        network_task->timeout = 3L;
        network_task->list = list;
        network_task->data_priv = NULL;
        network_task->http_method = CURLOPT_HTTPGET;
        memset(network_task->post_fields, 0, sizeof(network_task->post_fields));

        // if (tmp_vcd_conf->enable_rdp) {
        //     sprintf(url, "https://%s/api2/json/nodes/%s/qemu/%d/config",
        //             get_ip_port(), connect_data.node, connect_data.vmid);
        //     network_task->callback = button_enter_rdp_callback_task;
        // } else {
            sprintf(url, "https://%s/api2/extjs/nodes/%s/network", get_ip_port(), connect_data.node);
            network_task->callback = curl_get_server_ip_callback_task;
        // }
        strcpy(network_task->url, url);
        net_req_list_add(network_task);

    } else {
        // if (strcmp(connect_data.public_id, "") == 0) {
        //     messageBox("  自动登录失败！ ");//网络错误
        //     return;
        // }
        // char post[1000] = {0};
        // char url[480] = "https://";

        // prepare_for_public_curl(url, post);
        // struct curl_slist *list = NULL;
        // list = curl_slist_append(list, "Accept: application/json");
        // list = curl_slist_append(list, "Content-Type: application/json; charset=utf-8");

        // struct network_request_arg *network_task = (struct network_request_arg *)malloc(sizeof(struct network_request_arg));
        // network_task->timeout = 3L;
        // network_task->list = list;
        // network_task->hasreturn = TRUE;
        // network_task->callback = button_enter_callback;
        // strcpy(network_task->post_fields, post);
        // strcpy(network_task->url, url);

        // set_connecting_label();

        // net_req_list_add(network_task);
    }
}
